package org.hxd.admin.user.controller;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.hxd.admin.user.service.AdminUserService;
import org.hxd.client.products.service.ProductsService;
import org.hxd.pojo.ProductList;
import org.hxd.pojo.Products;
import org.hxd.pojo.User;
import org.hxd.utils.PageModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.UUID;

/**
 * company: www.abc.com
 * Author: Administrator
 * Create Data: 2021/5/28 0028
 */
@Controller
@RequestMapping("/admin/user")
public class usercontroller {
    @Autowired
    ProductsService productsService;
    @Autowired
    AdminUserService adminUserService;
    //判断用户登录
    @RequestMapping("/LoginUser")
    public String LoginUser(HttpSession session){
        User login_user = (User) session.getAttribute("Login_user");
        if(login_user!=null && login_user.getRole().equals("管理员")){
            return "admin/login/home";
        }else {
            return "admin/login/login";
        }
    }
    //验证登录账号
    @RequestMapping("/yLoginuser")
    @ResponseBody
    public String yLoginuser(User user){
        User user1 = adminUserService.yLoginuser(user);
        if(user1 != null) {
            return "OK";
        }else {
            return "FAIL";
        }
    }

    //条件查询商品信息
    @RequestMapping("/findTJproducts")
    public String findTJproducts(String msg, Products products,Double minprice, Double maxprice, Model model,@RequestParam(defaultValue = "1") Integer pageIndex){
        PageModel pageModel = new PageModel();
        pageModel.setPageSize(8);
        pageModel.setPageIndex(pageIndex);
        //查询记录数量
        int count = adminUserService.findProductsCount(products,minprice,maxprice);
        pageModel.setRocordCount(count);
        List<Products> productsList = adminUserService.findTJproducts(products,minprice,maxprice,pageModel);
        model.addAttribute("products",productsList);
        model.addAttribute("product",products);
        model.addAttribute("minprice",minprice);
        model.addAttribute("maxprice",maxprice);
        model.addAttribute("msg",msg);
        model.addAttribute("pageModel",pageModel);
        return "admin/products/list";
    }

    //添加书籍信息
    @RequestMapping("/addProduct")
    public String addProduct(HttpSession session, Products products, MultipartFile upload) throws IOException {
        // 1. 指定文件上传保存的位置
        String path = session.getServletContext().getRealPath("/productImg/images");
        // 判断该路径是否存在
        File file = new File(path);
        if (!file.exists() || !file.isDirectory()){
            file.mkdirs();
        }
        // 2. 获取上传文件的名称
        String filename = upload.getOriginalFilename();
        // 把文件的名称设置唯一值，uuid
        String uuid = UUID.randomUUID().toString().replace("-", "");
        if((uuid+filename).length()>=80){
            filename = uuid;
        }else {
            filename = uuid+"_"+filename;
        }
        // 3.上传文件

        upload.transferTo(new File(path + File.separator + filename));//File.separator相当于'\'
        products.setImgurl("/productImg/images"+File.separator+filename);
        products.setId(UUID.randomUUID().toString());
        //执行插入操作
        int rows = adminUserService.addProducts(products);
        String msg = "";
        if (rows > 0) {
            msg = "添加成功！";
        } else {
            msg = "添加成功！";
        }
        //解决重定向参数问题
        msg= new String(msg.getBytes("utf-8"),"iso-8859-1");
        return "redirect:/admin/user/findTJproducts?msg="+msg;
    }

    //Id查找修改书籍信息
    @GetMapping("/findProductById")
    public String findProductById(String id, Model model){
        Products product = productsService.findProductById(id);
        model.addAttribute("p",product);
        return "admin/products/edit";
    }
    //修改订单
    @PostMapping("/updateProduct")
    public String updateProduct(Products products,  MultipartFile upload, HttpSession session) throws IOException {
        if (!upload.isEmpty()) {//文件不能为空
            String path = session.getServletContext().getRealPath("/productImg/images");
            File file1 = new File(path);
            if (!file1.exists() || !file1.isDirectory()){
                file1.mkdirs();
            }
            Products product = productsService.findProductById(products.getId());
            File file = new File(path, product.getImgurl());
            if (file.exists()) {
                file.delete();//删除原来的文件
            }
            String filename = upload.getOriginalFilename();
            // 把文件的名称设置唯一值，uuid
            String uuid = UUID.randomUUID().toString().replace("-", "");
            if((uuid+filename).length()>=80){
                filename = uuid;
            }else {
                filename = uuid+"_"+filename;
            }
            upload.transferTo(new File(path + File.separator + filename));
            products.setImgurl("/productImg/images"+File.separator+filename);
        }
        int rows = adminUserService.updateProduct(products);
        String msg = "";
        if (rows > 0) {
            msg = "修改成功！";
        } else {
            msg = "修改成功！";
        }
        msg= new String(msg.getBytes("utf-8"),"iso-8859-1");
        return "redirect:/admin/user/findTJproducts?msg="+msg;
    }

    //删除订单信息
    @GetMapping("/deleteProduct")
    @ResponseBody
    public String deleteProduct(String id){
        int rows = adminUserService.deleteProduct(id);
        if(rows > 0){
            return "OK";
        }else {
            return "FAIL";
        }
    }

    //下载榜单
    @RequestMapping("/download")
    public void download(String year, String month, HttpServletResponse response) throws IOException {
        List<ProductList> productLists = adminUserService.finProductSalList(year,month);
        for (ProductList productList : productLists) {
            System.out.println(productList);
        }
        String filename = year + "年" + month + "月销售榜单";
//        String sheetName = month + "月销售榜单";
        String titleName = year + "年" + month + "月销售榜单";
        String[] columnName = {"商品名称","商品销量"};
        String[][] dataList = new String[productLists.size()][2];
        for(int i=0;i<productLists.size();i++){
            dataList[i][0] = productLists.get(i).getName();
            dataList[i][1] = productLists.get(i).getSalnum();
        }
        //创建excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        //创建excel中的sheet
        HSSFSheet sheet = wb.createSheet();
        //创建sheet的第一行
        HSSFRow row = sheet.createRow(0);
        //创建第一行第一个单元格
        HSSFCell cell = row.createCell(0);
        //合并第一行的两个单元格
        sheet.addMergedRegion(new CellRangeAddress(0,0,0,1));
        //给第一行的第一个合并后的单元格赋值
        cell.setCellValue(titleName);
        //创建第二行
        HSSFRow row1 = sheet.createRow(1);
        for(int i=0;i<2;i++){
            row1.createCell(i).setCellValue(columnName[i]);
        }
        //创建数据行
        for(int i=0;i<productLists.size();i++){
            row1 = sheet.createRow(i+2);
            for(int j=0;j<2;j++){
                row1.createCell(j).setCellValue(dataList[i][j]);
            }
        }
        String fileName = filename + ".xls";
        response.setContentType("application/ms-excel;charset=UTF-8");
        response.setHeader("content-Disposition","attachment;filename="+new String(fileName.getBytes( "utf-8" ),"ISO8859-1"));
        OutputStream outputStream = response.getOutputStream();
        wb.write(outputStream);
    }
}
